﻿@page "/edit"
@using Masa.Blazor.Presets;
@using MyToDoList.Data
@inject ToDoListService _todoSvc
@inject IJSRuntime JS

<MAppBar App>
    <NavLink @onclick="Back">
        <MButton icon>
            <MIcon>mdi-arrow-left</MIcon>
        </MButton>
    </NavLink>
    <MToolbarTitle>编辑</MToolbarTitle>
    <MSpacer></MSpacer>
    <NavLink @onclick="SaveAsync">
        <MButton icon>
            <MIcon>mdi-content-save-edit</MIcon>
        </MButton>
    </NavLink>
</MAppBar>

<!-- 根据应用组件来调整你的内容 -->
<MMain>
    <!-- 给应用提供合适的间距 -->
    <MContainer Fluid>
        <MList TwoLine>
            <MListItemGroup Color="primary">
                <MTextarea Solo @bind-Value="toDoModel.Content">
                </MTextarea>
            </MListItemGroup>
            <MListItemGroup Color="primary">
                <PMobileDateTimePicker @bind-Value="toDoModel.NotifyTime" Precision="DateTimePrecision.Minute" @key="DateTimePrecision.Minute">
                    <ActivatorContent>
                        <MButton Color="primary" Class="text-capitalize" Text @attributes="@context.Attrs">
                            @(ComputedDateTime)
                        </MButton>
                    </ActivatorContent>
                </PMobileDateTimePicker>
            </MListItemGroup>
        </MList>
    </MContainer>
</MMain>

@code {

    /// <summary>
    /// 接受Query参数
    /// </summary>
    [Parameter]
    [SupplyParameterFromQuery(Name = "todoId")]
    public string Id { get; set; }

    ToDoModel toDoModel = new();

    private DateTime ComputedDateTime
    {
        get
        {
            var _dateTime = toDoModel.NotifyTime;
            return new DateTime(_dateTime.Year, _dateTime.Month, _dateTime.Day, _dateTime.Hour, _dateTime.Minute, 1);
        }
    }

    protected override async Task OnInitializedAsync()
    {
        // todos = await _todoSvc.GetAll();
        if (!string.IsNullOrWhiteSpace(Id)&& Guid.TryParse(Id,out var guid) && guid!=Guid.Empty)
        {
            var todo = await _todoSvc.GetAsync(guid);
            toDoModel = todo ?? new ();
        }
    }

    private async Task SaveAsync()
    {
        try
        {
            if (toDoModel.Id == Guid.Empty)
            {
                await _todoSvc.AddAsync(toDoModel);
            }
            else
            {
                await _todoSvc.UpdateAsync(toDoModel);
            }
            await Back();
        }
        catch (Exception ex)
        {
            // todo 处理异常
        }
    }

    private async Task Back()
    {
        await JS.InvokeVoidAsync("window.history.back");
    }
}
